<?php
namespace Activity\Controllers;

use Commons\Jwt;
use Server\Models\Employee\MerchantMember;

/**
 *
 * @RoutePrefix("/sign")
 */
class SignController extends BaseController
{
    public function initialize()
    {
        return parent::initialize();
    }

    /**
     * @Post(
     *     "/in"
     * )
     * 登录
     * @throws \Exception
     */
    public function inAction()
    {
        $account  = $this->request->getPost('account');
        $password = $this->request->getPost('password');
        if ($account == '' || mb_strlen($account) > 11) {
            return $this->json([
                'code'      => 400,
                'msg'       => '帐号为空或格式输入不正确！',
                'timestamp' => time()
            ], 400);
        }
        if ($password == '') {
            return $this->json([
                'code'      => 400,
                'msg'       => '密码为空！',
                'timestamp' => time()
            ], 400);
        }
        $model = new MerchantMember();
        $user  = $model->getByAccount($account);
        if ($user === false) {
            return $this->json([
                'code'      => 400,
                'msg'       => '系统无该用户，请先注册!',
                'timestamp' => time()
            ], 400);
        }
        if ($user['password'] != md5($password)) {
            return $this->json([
                'code'      => 400,
                'msg'       => '账户或密码错误!',
                'timestamp' => time()
            ], 400);
        }
        if ($user['status'] != 1) {
            return $this->json([
                'code'      => 400,
                'msg'       => '您已禁止登录!',
                'timestamp' => time()
            ], 400);
        }
        return $this->json([
            'code'          => 200,
            'msg'           => '登录成功',
            'name'          => $user['name'],
            'jwt'           => (new Jwt())->encode([
                'uid'        => $user['uid'],
                'role'       => $user['role'],
                'iat'        => time(),
                'expires_in' => 3600
            ]),
            'refresh_token' => (new Jwt())->sign([
                'uid'  => $user['uid'],
                'role' => $user['role_id']
            ])
        ], 200);
    }

    /**
     * @Get(
     *     "/index"
     * )
     */
    public function indexAction()
    {

    }
}
